package com.margiel.rozkladowka.writer.impl;

import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.margiel.rozkladowka.model.Stop;
import com.margiel.rozkladowka.model.TimeTable;
import com.margiel.rozkladowka.model.Vehicle;
import com.margiel.rozkladowka.writer.Performer;
import com.margiel.rozkladowka.writer.Writer;

public class WriterImpl implements Writer {
	private final Logger log = Logger.getLogger(this.getClass());

	@Override
	public void writeTimeTable(List<Vehicle> vehicles, OutputStream outputStrem) throws IOException{
		log.debug("entering...");
		if (vehicles == null) {
			log.info("[writeTimeTable], vehicles null, returning...");
			return;
		}
		Performer performer = new PerformerImpl();
		List<String> stopsNames = performer.getStopList(vehicles);
		log.info("[writeTimeTable], no of vehices [" + vehicles.size() + "]");
		log.info("[writeTimeTable], no of stops [" + stopsNames.size() + "]");
		FileWriter fileWriter = new FileWriter("c:/rozkladowka/data/data.txt");
		fileWriter.write(vehicles.size()+"\r\n");
		fileWriter.write(stopsNames.size()+"\r\n");
		writeVehicles(vehicles, stopsNames, fileWriter);

		for (String stopName : stopsNames) {
			StringBuffer stopString = new StringBuffer(stopName + "[");
			int i = 0;
			for (Vehicle vehicle : vehicles) {
				if (vehicle.hasStop(stopName)) {
					stopString.append(i + " ");
				}
				i++;
			}
			stopString.append("]");
			log.info("[writeTimeTable], stopString " + stopString.toString());
			fileWriter.write(stopString.toString()+"\r\n");	
		}
		fileWriter.flush();
		fileWriter.close();
	}

	private void writeVehicles(List<Vehicle> vehicles, List<String> stopsNames, FileWriter fileWriter) throws IOException {
		for (Vehicle vehicle : vehicles) {
			StringBuffer vehicleString = new StringBuffer(vehicle.getNo());
			List<TimeTable> timeTabes = vehicle.getTimeTables();
			if (timeTabes == null) {
				log.info(" no time tables on vehicle[" + vehicle.getNo() + "]");
				continue;
			}
			for (TimeTable timeTable : timeTabes) {
				List<Stop> stops = timeTable.getStops();
				if (timeTabes == null) {
					log.info(" stops on timetable");
					continue;
				}
				vehicleString.append("[");
				for (Iterator<Stop> iterator = stops.iterator(); iterator.hasNext();) {
					Stop stop = (Stop) iterator.next();
					vehicleString.append(stopsNames.indexOf(stop.getName()));
					if (iterator.hasNext()) {
						vehicleString.append(" ");
					}
				}
				vehicleString.append("]");

			}
			log.info("[writeTimeTable], " + vehicleString.toString());
			fileWriter.write(vehicleString.toString()+"\r\n");
		}
	}
}
